package com.ttg.web.service.job.impl;

import com.google.common.util.concurrent.ListenableFuture;
import com.ttg.common.annotation.TaskRunMethod;
import com.ttg.common.enums.DimTypeEnum;
import com.ttg.common.exception.BaseException;
import com.ttg.common.vo.TaskResultVO;
import com.ttg.model.dto.QualityManageReportDTO;
import com.ttg.common.dto.TaskBaseDTO;
import com.ttg.model.dto.job.IndustryScoreDTO;
import com.ttg.model.po.IndustryPO;
import com.ttg.model.pojo.QualityManageIndustryReport;
import com.ttg.model.pojo.QualityManageTypeRule;
import com.ttg.model.vo.IndustryTwoLevelVO;
import com.ttg.web.dao.IndustryInfoDao;
import com.ttg.web.dao.QualityManageIndustryReportDao;
import com.ttg.web.dao.QualityManageTypeRuleDao;
import com.ttg.web.juc.TasktemplateHelper;
import com.ttg.web.service.job.IndustryClassificationJobService;
import com.ttg.web.service.job.QualityManageCommon;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Description：
 * Author: chenyou
 * Date: 2025/9/2 14:04
 * Company: ttg
 * Copyright: Copyright (c) 2025
 */
@Slf4j
@Service
@TaskRunMethod(value = "industryClassificationTask")
public class IndustryClassificationJobServiceImpl extends QualityManageCommon implements IndustryClassificationJobService {

    @Value("${tlinx.isJuc:false}")
    private volatile Boolean isJuc;//是否启用异步回调
    @Autowired
    private TasktemplateHelper tasktemplateHelper;
    @Autowired
    private QualityManageIndustryReportDao industryReportDao;
    @Autowired
    private QualityManageTypeRuleDao typeRuleDao;
    @Autowired
    private IndustryInfoDao industryInfoDao;

    /**
     * 行业分类计算
     *
     */
    @Override
    public TaskResultVO industryClassification(TaskBaseDTO reqDto) {
        reqDto = getCheckYearAndMonth(reqDto);
        //todo 写死几个自测行业分类，后续同步收单系统行业分类
        List<ListenableFuture<TaskResultVO>> futures = new ArrayList<>();
        List<TaskResultVO> results = new ArrayList<>();
        //1.查询所有二级行业分类
        List<IndustryTwoLevelVO> list = industryInfoDao.allTwoLevelList();
        List<QualityManageTypeRule> rules = typeRuleDao.getByDimType(DimTypeEnum.行业维度.getValue());
        if(rules==null){
            throw new BaseException("行业质量分类规则不能为空");
        }
        for (IndustryTwoLevelVO industry:list){
            IndustryScoreDTO industryScoreDTO = new IndustryScoreDTO();
            industryScoreDTO.setIndustry(industry);
            industryScoreDTO.setTypeRules(rules);
            if(isJuc){
                futures.add(tasktemplateHelper.submit(this,reqDto,industryScoreDTO));
            }else {
                TaskResultVO result = industryClassificationTask(reqDto,industryScoreDTO);
                results.add(result);
            }
        }
        return taskResult(results,futures,isJuc);
    }

    /**
     * 可异步处理的逻辑
     */
    public TaskResultVO industryClassificationTask(TaskBaseDTO reqDto, IndustryScoreDTO industryScoreDTO){
        try {
            IndustryTwoLevelVO industry = industryScoreDTO.getIndustry();
            List<QualityManageTypeRule> typeRules = industryScoreDTO.getTypeRules();
            //1. 获取行业质量报告,活跃率得分,清算成本得分,存款归集得分,加权得分
            QualityManageIndustryReport report = industryReportDao.getByUnique(reqDto.getYear(),reqDto.getMonth(), industry.getIndClsId1(), industry.getIndClsId2());

            QualityManageReportDTO reportDTO = new QualityManageReportDTO();
            reportDTO.setRepWeightScore(report.getRepWeightScore());
            reportDTO.setRepLivenessScore(report.getRepLivenessScore());
            reportDTO.setRepClearCostScore(report.getRepClearCostScore());
            reportDTO.setRepAvgScore(report.getRepAvgScore());

            Long qtrId = calculateQtrId(reportDTO, typeRules);
            if(qtrId==null){
                report.setRepQtrId(0L);
                report.setRepRemark("跑批年月："+(reqDto.getYear() + reqDto.getMonth())+",行业分类编号："+(industry.getIndClsId1() + "_" + industry.getIndClsId2())+"，计算分类错误,无法匹配分类");
            }else {
                report.setRepQtrId(qtrId);
            }
            industryReportDao.saveOrUpd(report);
        }catch (BaseException e) {
            e.printStackTrace();
            return taskReuslt(Status.FAIL.getValue(),false, e.getMsg());
        }catch (Exception ex){
            ex.printStackTrace();
            String exType = ex.getClass().getSimpleName();
            return taskReuslt(Status.FAIL.getValue(),false,"异常类型：" + exType + ",异常信息：" + ex.getMessage());
        }
        return taskReuslt(Status.SUCCESS.getValue(),false,"ok");
    }
}
